<?php 

class QuestionModel extends ViewModel{
	public $table='question';
	//与问题栏目关联
	public $view=array(
		'category'=>array('_type'=>'INNER'),
		'question'=>array('_type'=>'LEFT','_on'=>'category.cid=question.cid'),
		'user'=>array('_on'=>'question.uid=user.uid'),
		);
	//自动验证
	public $validate=array(
		array('qname','nonull','问题名不能为空',2,3),
		);
	//自动完成
	public $auto=array(//用于上传规范化格式
		array('qtime','strtotime','function',2,3),
		array('thumb','_autoThumb','method',2,3),
		);
	public function _autoThumb($v)
	{
		if (empty($v)) return $v;
		$v=current($v);
		return $v['path'];
	}
	//获取所有问题
	public function getList()
	{	
		//统计问题数量
		$count=$this->count();
		$page=new Page($count,20);
		$data=$this->limit($page->limit())->order(" qtime desc")->all();
		return array('data'=>$data,'page'=>$page->show());
	}
	//发布问题 
	public function addQuestion()
	{
		if ($this->create()) {
			$_POST['uid']=isset($_SESSION['uid'])?$_SESSION['uid']:0;
			$_POST['qtime']=time();
			if ($this->add($_POST)) {
				return true;
			}else{
				$this->error='发布失败';
			}
		}
	}
	//编辑问题
	public function editQuestion()
	{
		if ($this->create()) {
			if ($this->save()) {
				return true;
			}else{
				$this->error='编辑失败';
			}
		}
	}
	//删除问题
	public function delQuestion($qid)
	{
		$question=$this->find($qid);
		//删除问题下面对应的答案
		K('Answer')->where(" qid=$qid")->del();
		if (!empty($question['thumb']))unlink($question['thumb']);
		if ($this->where(" qid=$qid")->del()) {
			return true;
		}else{
			return $this->error="删除失败";
		}
	}
}

 ?>